import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {DialogService, ToastService} from 'ngx-weui';
import {Authenticate} from '../../core/authenticate.service';
import {Wallet} from './wallet';
import {WithdrawService} from './withdraw.service';
import {Observable, throwError} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {HttpErrorResponse} from '@angular/common/http';

@Component({
  selector: 'app-withdraw-deposit',
  templateUrl: './withdraw.component.html',
  styleUrls: ['./withdraw.component.scss']
})
export class WithdrawComponent implements OnInit {

  wallet$: Observable<Wallet>;

  loading = false;

  constructor(private auth: Authenticate,
              private route: ActivatedRoute,
              private router: Router,
              private srv: DialogService,
              private tsrv: ToastService,
              private service: WithdrawService) {
  }

  ngOnInit() {
    this.wallet$ = this.service.getWallet(this.auth.authenticator.info.openId)
      .pipe(map(w => {
        if (!w.alipay) {
          this.router.navigateByUrl('/bind-ali').then();
        }
        return w;
      }));
  }


  withdraw(wallet: any) {
    this.loading = true;
    this.wallet$ = this.service.withdraw(wallet)
      .pipe(tap(() => {
      this.loading = false;
      this.tsrv.show('提现成功');
    }), catchError(this.withdrawError));
  }

  private withdrawError(error: HttpErrorResponse) {
    return this.srv.show({
      title: '体现出错了',
      content: `<div class="weui-msg">
            <div class="weui-msg__text-area">
              <p class="weui-msg__desc"><i class="weui-icon-warn"></i>${error.error.message}</p>
            </div>
            </div>`, btns: [{text: '确认', type: 'primary', value: true}]
    }).pipe(map(() => {
      this.loading = false;
      return throwError(
        'Something bad happened; please try again later.');
    }));
  }
}
